package com.zzw.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisPubSubConfig {

    /**
     * 创建消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                  MessageListenerAdapter userActionListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 订阅用户操作频道
        container.addMessageListener(userActionListenerAdapter, new PatternTopic("user:actions"));
        return container;
    }

    /**
     * 创建消息监听适配器
     */
    @Bean
    public MessageListenerAdapter userActionListenerAdapter(UserActionSubscriber subscriber) {
        return new MessageListenerAdapter(subscriber, "onMessage");
    }
}
